package com.lyl.goods.controller;

import com.lyl.goods.pojo.Product;
import com.lyl.goods.pojo.ShoppingCart;
import com.lyl.goods.respository.CartRepository;
import com.lyl.goods.respository.ProductRepository;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;


@Controller
@Slf4j
public class ProductController {
    @Resource
    private ProductRepository productRepository;
    @Resource
    private CartRepository cartRepository;
    /***
     * @Description: 商品展示
     * @Author: liyunlong
     * @Date: 2024/3/1
     */
    @GetMapping("/product")
    public String getProductList(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize, HttpSession session, Model model) {
        String currentUser = (String) session.getAttribute("currentUser");
        model.addAttribute("userName", currentUser);
        // 根据pageNum和pageSize查询数据库获取相应分页的商品数据
        Page<Product> productList = productRepository.findAll(PageRequest.of((pageNum - 1), pageSize));
        long totalRecords = productRepository.count();
        int totalPages = (int) Math.ceil((double) totalRecords / pageSize); // 计算总页数
        int maxVisiblePages = 5; // 最大显示页码数
        // 将分页后的商品数据和分页信息添加到模型中
        model.addAttribute("productList", productList);
        model.addAttribute("maxVisiblePages", maxVisiblePages);
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("pages", totalPages);
        model.addAttribute("total", totalRecords);
        log.info("陈列商品信息");
        return "product/product";
    }

    /**
     * @Description: 添加商品
     * @Author: liyunlong
     * @Date: 2024/3/1
     */
    @GetMapping("/addProduct")
    public String showRForm() {
        return "/addProduct";
    }

    @RequestMapping(value = "/addProduct", method = RequestMethod.POST)
    public String insert(@RequestParam("name") String name,
                         @RequestParam("price") Integer price,
                         @RequestParam("stock") Integer stock,
                         @RequestParam("description") String description) {
        Product product = new Product();
        product.setName(name);
        product.setPrice(BigDecimal.valueOf(price));
        product.setStock(stock);
        product.setDescription(description);
        productRepository.save(product);
        log.info("添加商品信息，商品名为：{}", name);
        return "redirect:/product";
    }

    /**
     * @Description: 修改商品
     * @Author: liyunlong
     * @Date: 2024/3/1
     */
    @GetMapping("/updateProduct")
    public String showUpdateForm(@RequestParam("id") Long id, Model model) {
        Product product = getProduct(id);
        model.addAttribute("product", product);

        return "updateProduct"; // 返回更新商品页面
    }

    @NotNull
    private Product getProduct(Long id) {
        Product product = productRepository.getById(id);
        return product;
    }

    // 处理修改商品请求
    @PostMapping("/updateProduct")
    public String updateProduct(@ModelAttribute Product product) {
        String name = product.getName();
        productRepository.save(product);
        log.info("更新商品名为：{}的信息", name);
        return "redirect:/product";
    }


    /**
     * @Description: 商品详情
     * @Author: Liyunlong
     * @Date: 2024/3/1
     */
    @GetMapping("/detailProduct")
    public String showDetailForm(@RequestParam("id") Long id, Model model) {
        Product product = getProduct(id);
        model.addAttribute("product", product);
        log.info("查看商品：{}，的信息", product.getName());
        return "detailProduct";
    }


    /**
     * @Description: 商品详情
     * @Author: liyunlong
     * @Date: 2024/3/1
     */
    @GetMapping("/deleteProduct")
    public String showDeleteForm(@RequestParam("id") Long id, Model model) {
        Product product = productRepository.getReferenceById(id);
        model.addAttribute("product", product);
        return "deleteProduct"; // 返回更新商品页面
    }

    @RequestMapping("/deleteProduct")
    public String DeleteForm(@RequestParam("id") Long id) {
        productRepository.deleteById(id);
        log.info("删除商品信息，商品id为：{}", id);
        ShoppingCart byId = cartRepository.getByProductId(Math.toIntExact(id));
        Integer cartId = byId.getCartId();
        cartRepository.deleteById(Long.valueOf(cartId));
        log.info("同时删除与商品：{}，关联的购物车中的商品：{}", id, cartId);
        return "redirect:/product"; // 更新成功后重定向到商品列表页面
    }

    /**
     * @Description: 批量删除
     * @Author: liyunlong
     * @Date: 2024/3/1
     */

    //批量删除商品
    @PostMapping("/batchDeleteProduct")
    public String batchDeleteProduct(@RequestParam("selectedProductIds") List<Integer> selectedProductIds) {
        try {
            log.info("根据商品id:{}批量删除商品信息", selectedProductIds);
            for (Integer selectedProductId : selectedProductIds) {
                productRepository.deleteById(Long.valueOf(selectedProductId));
                ShoppingCart byProductId = cartRepository.getByProductId(selectedProductId);
                if (byProductId == null) {
                    return "redirect:/product"; // 重定向到商品列表页面
                }
                Integer cartId = byProductId.getCartId();
                cartRepository.deleteById(Long.valueOf(cartId));
            }
            return "redirect:/product"; // 重定向到商品列表页面
        } catch (Exception e) {
            // 处理异常情况
            e.printStackTrace();
            return "errorPage"; // 返回错误页面或者其他处理方式
        }
    }
}
